package com.thinkit.bigdata.web.controller.system;

import com.thinkit.bigdata.core.feature.orm.mybatis.Page;
import com.thinkit.bigdata.core.util.StringUtil;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.model.sys.SysOperateLog;
import com.thinkit.bigdata.web.model.sys.SysOperateLogExample;
import com.thinkit.bigdata.web.service.log.SystemOperateLogService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Modify by lihongli on 2018/9/12
 */
@Controller
@RequestMapping("systemManager")
public class SystemOperatorController {

    private Logger logger = Logger.getLogger(SystemOperatorController.class);

    @Resource
    private SystemOperateLogService systemOperateLogService;

    /**
     * 跳转到日志管理页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/logSearch")
    public String sysLog(HttpServletRequest request) {
        logger.info("请求进入日志管理页面");
        return "RunManageView/log";
    }

    /**
     * 日志分页查询
     *
     * @param request
     * @param sortOrder
     * @param sortName
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("/operateLogByPage")
    public Page<SysOperateLog> operateLogByPage(
            HttpServletRequest request,
            @RequestParam(value = "sortOrder") String sortOrder,
            @RequestParam(value = "sortName") String sortName,
            @RequestParam(value = "pageNum", defaultValue = "1") final int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") final int pageSize) {
        // 查询参数 操作人名称、资源名称
        String userName = request.getParameter("userName");
        String resourceName = request.getParameter("resourceName");
        // 查询开始时间
        String dateStart = request.getParameter("dateStart");
        Date startDate = formateDate(dateStart);
        // 查询结束时间
        String dateEnd = request.getParameter("dateEnd");
        Date endDate = formateDate(dateEnd);
        String logTxt = "【操作日志分页查询】";
        logger.info(logTxt + "查询条件: pageNum=" + pageNum);
        logger.info(logTxt + "查询条件: pageSize=" + pageSize);
        logger.info(logTxt + "查询条件: userName=" + userName);
        logger.info(logTxt + "查询条件: resourceName=" + resourceName);
        logger.info(logTxt + "查询条件: dateStart=" + dateStart);
        logger.info(logTxt + "查询条件: dateEnd=" + dateEnd);
        // 查询条件设置
        SysOperateLogExample example = new SysOperateLogExample();
        SysOperateLogExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotEmpty(userName)) {
            criteria.andUsernameLike("%" + userName + "%");
        }
        if (StringUtil.isNotEmpty(resourceName)) {
            criteria.andResourcenameLike("%" + resourceName + "%");
        }
        if (startDate != null) {
            criteria.andOpttimeGreaterThan(startDate);
        }
        if (endDate != null) {
            criteria.andOpttimeLessThan(endDate);
        }

        // 排序方式设置
        example.setOrderByClause(sortName + " " + sortOrder);
        // 分页信息设置
        Page<SysOperateLog> page = new Page<>(pageNum, pageSize);
        systemOperateLogService.selectByExampleAndPage(page, example);
        logger.info(logTxt + "查询完成，共计查询到" + page.getResult().size() + "条日志信息");
        return page;
    }

    /**
     * 日志写入接口
     *
     * @param request
     * @param operateLog
     */
    @ResponseBody
    @RequestMapping("/insertLog")
    public void insertLog(HttpServletRequest request, SysOperateLog operateLog) {
        // 记录操作人
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
        operateLog.setUserid(user.getId());
        operateLog.setUsername(user.getUsername());
        operateLog.setOpttime(new Date());
        // 如果资源id存在写入日志
        if (operateLog.getResourceid() != null) {
            // 如果资源名称存在 则用默认写入日志方法 否则写入日志时 自动写入资源名称
            if (StringUtil.isNotEmpty(operateLog.getResourcename()))
                systemOperateLogService.insertSelective(operateLog);
            else systemOperateLogService.insertLog(operateLog);
        }
    }

    /**
     * 格式化YYYY-MM-DD的时间字符串为Date类型
     *
     * @param dateStr
     * @return
     */
    private Date formateDate(String dateStr) {
        if (StringUtil.isNotEmpty(dateStr)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            try {
                return sdf.parse(dateStr);
            } catch (ParseException e) {
                return null;
            }
        } else {
            return null;
        }
    }
}
